package com.kingdee.pda.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.basecommon.http.MyObserver;
import com.example.basecommon.http.RxHelper;
import com.example.basecommon.http.rxjava.BaseResponse;
import com.example.basecommon.http.rxjava.HttpUtils;
import com.example.basecommon.utils.ConstantUtil;
import com.example.basecommon.utils.SpeakUtils;
import com.kingdee.pda.Api;
import com.kingdee.pda.R;
import com.kingdee.pda.adapter.WarehouseLocationAdapter;
import com.kingdee.pda.adapter.WarehouseLocationAdapter2;
import com.kingdee.pda.callback.MyTouchLinstener;
import com.kingdee.pda.entity.LocationBalanceRes;
import com.kingdee.pda.entity.Warehouse;
import com.kingdee.pda.entity.WarehouseLocation;
import com.kingdee.pda.plugins.http.common.OnRequestCallback;
import com.kingdee.pda.plugins.http.serverinterface.IQueryLocationStock;
import com.kingdee.pda.plugins.http.serverinterface.impl.QueryLocationStockImpl;
import com.kingdee.pda.ui.widget.CustomHScrollView;
import com.kingdee.pda.util.CommonUtil;
import com.kingdee.pda.util.GlideUtils;
import com.kingdee.pda.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 库位库存查询
 * Created by zhanlg
 * DATE 2021/5/25
 * TIME 14:51
 */
public class QueryLocationStockActivity extends BaseTitleActivity {

    private ImageView mIvGoodsPic;
    private TextView mTvGoodsName;
    private TextView mTvSpecName;
    private TextView mTvSKUNum;
    private TextView mTvGoodsNum;
    private TextView mTvGoodsBarcode;
    private TextView mTvStockCount;
    private CustomHScrollView customHScrollView1;
    private CustomHScrollView customHScrollView2;

    private ListView mListView;
    private ListView list_view_stock;
    private TextView mTvNoDataTips;
    private IQueryLocationStock mIQueryLocationStock;
    private WarehouseLocationAdapter mAdapter;
    private WarehouseLocationAdapter2 mAdapter2;

    private EditText et_skuCode;
    @BindView(R.id.rg_queryType)
    RadioGroup rg_queryType;
    @BindView(R.id.rb_querySku)
    RadioButton rb_querySku;
    @BindView(R.id.tv_locationCode)
    TextView tv_locationCode;

    public static void actionStart(Context context) {
        context.startActivity(new Intent(context, QueryLocationStockActivity.class));
    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        super.onActivityCreate(savedInstanceState);
        setContentView(R.layout.activity_query_location_stock);
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("库位库存查询");
        mIvGoodsPic = findViewById(R.id.iv_goods_pic);
        mTvGoodsName = findViewById(R.id.tv_goods_name);
        mTvSpecName = findViewById(R.id.tv_spec_name);
        mTvSKUNum = findViewById(R.id.tv_sku_num);
        mTvGoodsNum = findViewById(R.id.tv_goods_num);
        mTvGoodsBarcode = findViewById(R.id.tv_goods_barcode);
        mTvStockCount = findViewById(R.id.tv_stock_count);

        customHScrollView1= findViewById(R.id.h_scrollView);
        customHScrollView2= findViewById(R.id.h_scrollView2);

        mListView = findViewById(R.id.list_view);
        list_view_stock = findViewById(R.id.list_view_stock);

        mTvNoDataTips = findViewById(R.id.tv_no_data_tips);
        et_skuCode = findViewById(R.id.et_skuCode);
        et_skuCode.setOnEditorActionListener(new QueryLocationStockActivity.OnActionListener());

        MyTouchLinstener myTouchLinstener = new MyTouchLinstener(customHScrollView1);
        mListView.setOnTouchListener(myTouchLinstener);

        MyTouchLinstener myTouchLinstener2 = new MyTouchLinstener(customHScrollView2);
        list_view_stock.setOnTouchListener(myTouchLinstener2);

        rg_queryType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (rb_querySku.isChecked()) {
                    findViewById(R.id.layput_sku).setVisibility(View.VISIBLE);
                    findViewById(R.id.layout_stock).setVisibility(View.GONE);
                    findViewById(R.id.layout_skuinfo).setVisibility(View.VISIBLE);
                    et_skuCode.setHint("请扫描商品条码");
                } else {
                    findViewById(R.id.layput_sku).setVisibility(View.GONE);
                    findViewById(R.id.layout_stock).setVisibility(View.VISIBLE);
                    findViewById(R.id.layout_skuinfo).setVisibility(View.GONE);
                    et_skuCode.setHint("请扫描或输入库位编码");
                }

                CommonUtil.requestFocusAndClearText(et_skuCode);
            }
        });
    }


    @Override
    protected void initData() {
        super.initData();
        mAdapter = new WarehouseLocationAdapter(this,customHScrollView1);
        mListView.setAdapter(mAdapter);

        mAdapter2 = new WarehouseLocationAdapter2(this, customHScrollView2);
        list_view_stock.setAdapter(mAdapter2);
    }

    @Override
    public void changeWarehouse(Warehouse warehouse) {
        initNoDataView();
    }


    @Override
    public void getScanResult(String scanResult) {
        super.getScanResult(scanResult);
        if (TextUtils.isEmpty(scanResult)) {
            ToastUtils.showShort(QueryLocationStockActivity.this, "扫码结果为空，请重试");
            return;
        }
        if (getCurrentWarehouse() == null) {
            ToastUtils.showShort(QueryLocationStockActivity.this, "当前仓库信息获取失败");
            return;
        }

        et_skuCode.setText(scanResult);
        if (rb_querySku.isChecked()) {
            if (TextUtils.isEmpty(CommonUtil.skuCodeSplit(this, scanResult))) {
                SpeakUtils.speakWithToast(this, "商品条码截取结果为空，请检查输入和截图规则", false, false);
                return;
            }
            scanResult = CommonUtil.skuCodeSplit(this, scanResult);
            queryLocationStockInfo(scanResult);
        } else {
            getStockData(scanResult);
        }
        et_skuCode.setText(scanResult);
    }

    private void queryLocationStockInfo(String barcode) {
        showLoadingDialog();
        if (mIQueryLocationStock == null) {
            mIQueryLocationStock = new QueryLocationStockImpl();
        }
        mIQueryLocationStock.queryLocationStock(getCurrentWarehouse().getId(), barcode, new OnRequestCallback<JSONObject>() {
            @Override
            public void onFailedCallback(boolean isRequestCallback, final String errorMsg) {
                super.onFailedCallback(isRequestCallback, errorMsg);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        initNoDataView();
                        ToastUtils.showLong(QueryLocationStockActivity.this, errorMsg);
                    }
                });
            }

            @Override
            public void onSuccessCallback(final JSONObject result, Object object) {
                super.onSuccessCallback(result, object);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        showView(result);
                    }
                });
            }
        });
    }

    private void initNoDataView() {
        mTvGoodsName.setText("商品名称：—");
        mTvSpecName.setText("规格名称：—");
        mTvSKUNum.setText("SKU 编码：—");
        mTvGoodsNum.setText("商品编码：—");
        mTvGoodsBarcode.setText("商品条码：—");
        mTvStockCount.setText("库存总数：—");
        mIvGoodsPic.setImageResource(R.mipmap.image_pic_default);
        mTvNoDataTips.setVisibility(View.VISIBLE);
        mListView.setVisibility(View.GONE);
        CommonUtil.requestFocusAndNoClearText(et_skuCode);
    }

    private void showView(JSONObject data) {
        if (data != null) {
            mTvGoodsName.setText("商品名称：" + data.optString("itemName"));
            mTvSpecName.setText("规格名称：" + data.optString("specName"));
            mTvSKUNum.setText("SKU 编码：" + data.optString("skuCode"));
            mTvGoodsNum.setText("商品编码：" + data.optString("itemCode"));
            mTvGoodsBarcode.setText("商品条码：" + data.optString("itemBarcode"));
            mTvStockCount.setText("库存总数：" + CommonUtil.formatDoubleToString(data.optDouble("baseqtyCount")));
            GlideUtils.loadImage(this, data.optString("pictureUrl", ""), mIvGoodsPic);
            getWarehouseLocationData(data);
            CommonUtil.requestFocusAndNoClearText(et_skuCode);
        } else {
            initNoDataView();
        }
    }

    private void getWarehouseLocationData(JSONObject data) {
        try {
            JSONArray array = data.getJSONArray("balanceList");
            if (array != null && array.length() > 0) {
                List<WarehouseLocation> whLocationList = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    WarehouseLocation whLocation = new WarehouseLocation();
                    JSONObject json = array.getJSONObject(i);
                    whLocation.setWarehouseNum(json.optString("warehouseCode"));
                    whLocation.setWarehouseName(json.optString("warehouseName"));
                    whLocation.setLocationId(json.optLong("locationId"));
                    whLocation.setLocationCode(json.optString("locationCode"));
                    whLocation.setLocationName(json.optString("locationName"));
                    whLocation.setAreaNumber(json.optString("areaCode"));
                    whLocation.setAreaName(json.optString("areaName"));
                    whLocation.setAreaType(json.optInt("areaType"));
                    whLocation.setBaseqty(json.optInt("baseqty"));
                    whLocation.setReservoeQty(json.optInt("reservoeqty"));
                    whLocation.setAvbbaseqty(json.optInt("avbbaseqty"));
                    whLocation.setPreinbaseqty(json.optInt("preinbaseqty"));
                    whLocation.setOwnerName(json.optString("ownerName"));
                    whLocation.setInvStatusId(json.optLong("invStatusId"));
                    whLocation.setInvStatusName(json.optString("invStatusName"));

                    whLocationList.add(whLocation);
                }
                mTvNoDataTips.setVisibility(View.GONE);
                mListView.setVisibility(View.VISIBLE);
                mAdapter.setData(whLocationList);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mTvNoDataTips.setVisibility(View.VISIBLE);
        mListView.setVisibility(View.GONE);
    }

    public void getStockData(String locationCode) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("warehouseId", getCurrentWarehouse().getId());
        map.put("locationCode", locationCode);

        MyObserver<List<LocationBalanceRes>> myObserver = new MyObserver<List<LocationBalanceRes>>(this) {
            @Override
            public void onSuccess(BaseResponse<List<LocationBalanceRes>> result) {
                mAdapter2.setData(result.data);
                tv_locationCode.setText("库位编码：" + et_skuCode.getText().toString());
                CommonUtil.requestFocusAndClearText(et_skuCode);
            }

            @Override
            public void onFailure(BaseResponse result, String msg) {
                SpeakUtils.speakWithToast(QueryLocationStockActivity.this, msg, false, false);
                mAdapter2.setData(new ArrayList<>());
                CommonUtil.requestFocusAndClearText(et_skuCode);
            }
        };
        HttpUtils.request(Api.class)
                .pda_location_stock_query(ConstantUtil.PDA_STOCK_QUERY, map)
                .compose(RxHelper.observableIO2Main(this))
                .subscribe(myObserver);
    }

    class OnActionListener implements TextView.OnEditorActionListener {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                String input = v.getText().toString().trim();
                if (TextUtils.isEmpty(input)) {
                    ToastUtils.showShort(QueryLocationStockActivity.this, "扫码结果为空，请重试");
                    return true;
                }
                if (getCurrentWarehouse() == null) {
                    ToastUtils.showShort(QueryLocationStockActivity.this, "当前仓库信息获取失败");
                    return true;
                }
                if (rb_querySku.isChecked()) {
                    String skuSplit = CommonUtil.skuCodeSplit(QueryLocationStockActivity.this, input);
                    if (TextUtils.isEmpty(skuSplit)) {
                        SpeakUtils.speakWithToast(QueryLocationStockActivity.this, "商品条码截取结果为空，请检查输入和截图规则", false, false);
                        return true;
                    }
                    queryLocationStockInfo(skuSplit);
                } else {
                    getStockData(input);
                }
                return true;
            }
            return false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
